<template>
  <div :style="`height: ${height}`">
    <iframe :src="url" style="width: 100%; height: 100%" />
  </div>
</template>

<script setup>
  import {
    ref,
    onMounted,
    onBeforeUnmount,
    getCurrentInstance
  } from 'vue'
  import {
    useRoute
  } from 'vue-router'
  import {
    getToken
  } from "@/utils/auth"

  // 响应式变量
  const height = ref('')
  const url = ref('')

  // 路由实例
  const route = useRoute()

  // 获取组件实例（用于访问全局属性）
  const {
    proxy
  } = getCurrentInstance()

  // 处理消息事件
  const handleMessage = (event) => {
    switch (event.data.method) {
      case "close":
        close();
        break;
    }
  }

  // 关闭页面方法
  const close = () => {
    const obj = {
      path: "/flow/form"
    };
    if (proxy?.$tab) {
      proxy.$tab.closeOpenPage(obj);
    } else {
      console.warn('$tab 全局属性未定义')
    }
  }

  // 组件挂载时
  onMounted(() => {
    // 计算高度
    height.value = `${document.documentElement.clientHeight - 94.5}px`;

    // 构建URL
    const baseUrl = `${import.meta.envVITE_APP_BASE_API}/warm-flow-ui/index.html`;
    const params = new URLSearchParams({
      type: 'form',
      id: route.params.id,
      disabled: route.query.disabled || '',
      Authorization: `Bearer ${getToken()}`
    });
    url.value = `${baseUrl}?${params.toString()}`;

    // 添加消息事件监听
    window.addEventListener("message", handleMessage);
  })

  // 组件卸载前
  onBeforeUnmount(() => {
    // 移除消息事件监听
    window.removeEventListener("message", handleMessage);
  })
</script>